package com.manzuo.framework.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 处理{@link UseWriteDataSource}注解的AspectJ切面。
 * 
 * @author 高恒
 */
@Aspect
public class UseWriteDataSourceAspect {

	private static Logger logger = LoggerFactory.getLogger(UseWriteDataSourceAspect.class);
	
	@SuppressWarnings("unused")
	@Pointcut("@annotation(com.manzuo.framework.datasource.UseWriteDataSource)")
	private void useWriteDataSource() {};
	
	@Around("useWriteDataSource()")
	public Object doUseWriteDataSource(ProceedingJoinPoint pjp) throws Throwable {
		Object object = null;
		boolean isTargetThrows = false;
		try {
			ReadWriteContext.toggleWrite();
			try {
				object = pjp.proceed();
			} catch(Throwable t) {
				isTargetThrows = true;
				throw t;
			}			
			ReadWriteContext.reset();			
		} catch(Throwable t) {
			if(isTargetThrows) {
				throw t;
			} else {
				logger.error("Error when toggle read imm", t);
			}
		}
		return object;		
	}
	
}
